#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

// 颜色计算工具函数
function hexToHsl(hex) {
  const r = parseInt(hex.slice(1, 3), 16) / 255;
  const g = parseInt(hex.slice(3, 5), 16) / 255;
  const b = parseInt(hex.slice(5, 7), 16) / 255;

  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  let h, s, l = (max + min) / 2;

  if (max === min) {
    h = s = 0;
  } else {
    const d = max - min;
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
    switch (max) {
      case r: h = (g - b) / d + (g < b ? 6 : 0); break;
      case g: h = (b - r) / d + 2; break;
      case b: h = (r - g) / d + 4; break;
    }
    h /= 6;
  }

  return [Math.round(h * 360), Math.round(s * 100), Math.round(l * 100)];
}

function hslToHex(h, s, l) {
  h /= 360;
  s /= 100;
  l /= 100;

  const c = (1 - Math.abs(2 * l - 1)) * s;
  const x = c * (1 - Math.abs((h * 6) % 2 - 1));
  const m = l - c / 2;

  let r, g, b;

  if (0 <= h && h < 1/6) {
    r = c; g = x; b = 0;
  } else if (1/6 <= h && h < 2/6) {
    r = x; g = c; b = 0;
  } else if (2/6 <= h && h < 3/6) {
    r = 0; g = c; b = x;
  } else if (3/6 <= h && h < 4/6) {
    r = 0; g = x; b = c;
  } else if (4/6 <= h && h < 5/6) {
    r = x; g = 0; b = c;
  } else {
    r = c; g = 0; b = x;
  }

  r = Math.round((r + m) * 255);
  g = Math.round((g + m) * 255);
  b = Math.round((b + m) * 255);

  return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
}

// 生成色系变量
function generateColorPalette(primaryColor, colorName = 'primary') {
  const [h, s, l] = hexToHsl(primaryColor);
  const palette = {};

  // 生成10个色阶
  const lightness = [95, 85, 75, 65, 50, 35, 25, 15, 10, 5];
  
  lightness.forEach((lightValue, index) => {
    const level = (index + 1) * 100;
    const color = hslToHex(h, s, lightValue);
    palette[`--color-${colorName}-${level}`] = color;
  });

  return palette;
}

// 生成元素色系变量
function generateElementColors(palette, colorName = 'primary') {
  const elementColors = {};
  
  // 文本色系
  elementColors[`--text-${colorName}`] = palette[`--color-${colorName}-700`];
  elementColors[`--text-${colorName}-light`] = palette[`--color-${colorName}-500`];
  elementColors[`--text-${colorName}-lighter`] = palette[`--color-${colorName}-300`];
  
  // 背景色系
  elementColors[`--bg-${colorName}`] = palette[`--color-${colorName}-500`];
  elementColors[`--bg-${colorName}-light`] = palette[`--color-${colorName}-100`];
  elementColors[`--bg-${colorName}-dark`] = palette[`--color-${colorName}-800`];
  elementColors[`--bg-${colorName}-hover`] = palette[`--color-${colorName}-600`];
  elementColors[`--bg-${colorName}-active`] = palette[`--color-${colorName}-700`];
  
  // 边框色系
  elementColors[`--border-${colorName}`] = palette[`--color-${colorName}-300`];
  elementColors[`--border-${colorName}-light`] = palette[`--color-${colorName}-200`];
  elementColors[`--border-${colorName}-dark`] = palette[`--color-${colorName}-500`];
  elementColors[`--border-${colorName}-hover`] = palette[`--color-${colorName}-400`];
  
  // 按钮色系
  elementColors[`--btn-${colorName}`] = palette[`--color-${colorName}-500`];
  elementColors[`--btn-${colorName}-hover`] = palette[`--color-${colorName}-600`];
  elementColors[`--btn-${colorName}-active`] = palette[`--color-${colorName}-700`];
  elementColors[`--btn-${colorName}-disabled`] = palette[`--color-${colorName}-300`];
  
  // 链接色系
  elementColors[`--link-${colorName}`] = palette[`--color-${colorName}-600`];
  elementColors[`--link-${colorName}-hover`] = palette[`--color-${colorName}-700`];
  elementColors[`--link-${colorName}-visited`] = palette[`--color-${colorName}-800`];
  
  return elementColors;
}

// 生成CSS变量字符串
function generateCSSVariables(variables) {
  let css = ':root {\n';
  Object.entries(variables).forEach(([key, value]) => {
    css += `  ${key}: ${value};\n`;
  });
  css += '}\n';
  return css;
}

// 主函数
function generateColors(primaryColor, options = {}) {
  const {
    colorName = 'primary',
    includeElements = false,
    outputPath = 'src/styles/colors.scss'
  } = options;

  // 验证颜色格式
  if (!/^#[0-9A-Fa-f]{6}$/.test(primaryColor)) {
    throw new Error('请提供有效的十六进制颜色值，格式如: #3b82f6');
  }

  // 生成色系变量
  const palette = generateColorPalette(primaryColor, colorName);
  let allVariables = { ...palette };

  // 如果需要，生成元素色系变量
  if (includeElements) {
    const elementColors = generateElementColors(palette, colorName);
    allVariables = { ...allVariables, ...elementColors };
  }

  // 生成CSS
  const css = generateCSSVariables(allVariables);

  // 确保输出目录存在
  const outputDir = path.dirname(outputPath);
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  // 写入文件
  fs.writeFileSync(outputPath, css);

  console.log(`✅ 色系变量已生成到: ${outputPath}`);
  console.log(`🎨 主色系: ${primaryColor}`);
  console.log(`📊 生成了 ${Object.keys(palette).length} 个色系变量`);
  if (includeElements) {
    console.log(`🧩 生成了 ${Object.keys(allVariables).length - Object.keys(palette).length} 个元素色系变量`);
  }
}

// 命令行接口
function main() {
  const args = process.argv.slice(2);
  
  if (args.length === 0 || args.includes('--help') || args.includes('-h')) {
    console.log(`
🎨 色系CSS变量生成工具

用法:
  node tools/colors/index.js <主色系> [选项]

参数:
  <主色系>     十六进制颜色值 (如: #3b82f6)

选项:
  --name <名称>          色系名称 (默认: primary)
  --elements             生成元素色系变量
  --output <路径>        输出文件路径 (默认: src/styles/colors.scss)
  --help, -h             显示帮助信息

示例:
  node tools/colors/index.js #3b82f6
  node tools/colors/index.js #10b981 --name success --elements
  node tools/colors/index.js #ef4444 --name danger --elements --output src/styles/danger.scss
    `);
    return;
  }

  const primaryColor = args[0];
  const options = {};

  // 解析选项
  for (let i = 1; i < args.length; i++) {
    if (args[i] === '--name' && i + 1 < args.length) {
      options.colorName = args[i + 1];
      i++;
    } else if (args[i] === '--elements') {
      options.includeElements = true;
    } else if (args[i] === '--output' && i + 1 < args.length) {
      options.outputPath = args[i + 1];
      i++;
    }
  }

  try {
    generateColors(primaryColor, options);
  } catch (error) {
    console.error('❌ 错误:', error.message);
    process.exit(1);
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  main();
}

module.exports = { generateColors, generateColorPalette, generateElementColors }; 